// This file is automatically included by javascript_include_tag :defaults

// Every time a page loads, this code is executed...
$(function() {
  $.ajaxSetup({ type: "POST", timeout: 2500 })
  
  // Flash message effects
  flash_message = $("#flash_message");
  if (flash_message.children(".flash_message").hasClass("error")) flash_message.effect('shake');
  else {
    flash_message.children(".flash_message")
      .effect('pulsate', {times: 2, speed: 'slow'}, setTimeout(function() { flash_message.slideUp(); }, 3000));
  }
  
  // Observe the active_bundle select and redirect when changed, also hide the switch button
  $('#switch_bundle_form #bundle_id')
    .next('button').hide()
  .end().bind('change', function() {
    $(this).parents('form').submit()
  });
  
  $("#new_bundle_button").click(function(event) {
    event.preventDefault();
    $('#new_bundle_control').fadeIn().children('input').focus();
  });
  
  // Make the new bundle form submit via AJAX
  new_bundle_ajax_setup = function() {
    $("#new_bundle").submit(function(event) {
      event.preventDefault();
      $.ajax({
        url: this.action,
        data: $(this).serialize(),
        error: function(xhr, status) {
          if (xhr.status == 302) {
            window.location.assign(xhr.responseText);
          } else {
            $("#new_bundle_control").html(xhr.responseText);
            new_bundle_ajax_setup();
          };
        }
      });
    });
  };
  new_bundle_ajax_setup();
  
  // Reveal the header explanation
  show_header_explanation = function(clicked) {
    $(clicked).hide()
      .parent("h2")
        .next(".explanation")
          .slideDown("fast");
  }

  // Hide the header explanation
  hide_header_explanation = function(clicked) {
    $(clicked).parents(".explanation").hide("fast");
  }

  // Calculate the frequency of each element in an array
  frequency = function(arr) {
    freq = {};
    $.each(arr, function() {
      if (freq[this]) {
        freq[this] += 1;
      } else {
        freq[this] = 1;
      }
    });
    return freq;
  };
});

// Bundle "plugin"
(function($){
  $(function() {
    
    // Add a posting to the active_bundle
    create_bundling = function(posting_id) {
      $.ajax({ url: "/bundlings", dataType: "json",
        data: { posting_id: posting_id },
        success: function(json) {
          $("#current_bundlings_view .bundle_contents").html(json.content);
          bind_remove_links();
          setTimeout(function() { $("#"+json.dom_id).effect("highlight"); }, 10);
        }
      });
    };
    
    // Remove a posting from the active_bundle
    destroy_bundling = function(bundle_id) {
      $.ajax({ url: "/bundlings/"+bundle_id, dataType: "json",
        data: { _method: "delete" }, 
        success: function(json) {
          $("#"+json.dom_id).fadeOut("slow", function() {
            $("#current_bundlings_view .bundle_contents").html(json.content);
            bind_remove_links();
            $(this).remove();
          });
        }
      });
    };
    
    // Make the available postings draggable
    $("#all_postings .posting").draggable({
      cursor: 'move', distance: 5, revert: true, zIndex: 1001, cursorAt: { left: 315 }
    });
    
    // Make the active bundle into a drop target for adding
    $(".active_bundle").droppable({
      accept: ".posting",
      hoverClass: "posting_hovering",
      drop: function(event, ui) {
        var ids = ui.draggable.attr("id").split("_posting_");
        var posting_id = ids[1];
        ui.draggable.css({ left: 0, top: 0 }); // prevent revert animation
        create_bundling(posting_id);
      }
    });
    
    // Bind the click event to the remove icon for ech posting in the active_bundle
    bind_remove_links = function() {
      $(".bundled_posting .remove").click(function(event) {
        event.preventDefault();
        bundling_id = $(this).parent().attr("id").replace("bundling_", "");
        destroy_bundling(bundling_id);
      });
    }
    bind_remove_links();
    
    // Make the sharing form submit via ajax
    $("#share form").submit(function(event) {
      event.preventDefault();
      $.post($(this).attr("action"), $(this).serialize(), function() { $("#share").fadeOut() });
    });
    
    // Move a bundle into the comparison area
    add_to_compare = function(bundle_id) {
      $.post("/bundles/add", { id: bundle_id }, function(response) {
        $("#compare_bundles").html(response);
        compare();
        attach_remove_behavior();
      });
    };
    
    // Bind the click even on add buttons to move them into the comparison area
    $("#bundles_list .add").click(function(event) {
      event.preventDefault();
      console.log($(this));
      add_to_compare($(this).parents(".comparable_bundle").attr("id").replace("bundle_", ""));
    });
    
    // Move a bundle out of the comparison area
    remove_from_compare = function(bundle_id) {
      $.post("/bundles/remove", {id: bundle_id }, function(response) {
        $("#compare_bundles").html(response);
        compare();
        attach_remove_behavior();
      });
    };
    
    // Bind the click event on the remove buttons to remove the bundle from the comparison area
    attach_remove_behavior = function() {
      $("#compare_bundles .remove").click(function(event) {
        event.preventDefault();
        console.log($(this))
        remove_from_compare($(this).parents('.comparing_bundle').attr("id").split("_bundle_")[1]);
      });
    };
    attach_remove_behavior();
    
    
    // Map the frequency of occurrence of a Posting in the comparison area to css classes
    frequency_classes = {
      "1": "not_common",
      "2": "semi_common",
      "3": "common"
    };
    
    // Compare the postings in each compared bundle and assign the proper css class and width
    compare = function() {
      postings = [];
      $("#compare_bundles .posting").each(function() {
        postings.push($(this).attr("id").split('_posting_')[1]);
      });
      freq = frequency(postings);
      $("#compare_bundles .posting").each(function() {
        posting_id = $(this).attr("id").split('_posting_')[1];
        $(this).addClass(frequency_classes[freq[posting_id]]);
      });
      comparing = $("#bundles_basket .bundle");
      comparing.css({width: Math.floor(100.0 / comparing.length)+"%", float: 'left'})
    };
    compare();
  });
})(jQuery);
